<template>
  <div id="top">
    <transition name="fade">
      <header id="nav" v-show="navShow">
        <div class="left">
          <img src="../../static/logo.jpg" alt="" />
          <span>酷茄音乐</span>
        </div>
        <div class="nav">
          <span
            v-for="(item, index) in navList"
            :key="index"
            class="span"
            @click="navChoose(index)"
            :class="[num == index ? 'active' : '']"
          >
            <span>{{ item.value }} </span>
            <i class="ingIcno" v-show="index == 1 || index == 3"></i
          ></span>
        </div>

        <div class="search">
          <transition name="fade">
            <div
              class="searchHot"
              v-show="searchHotShow == true && inputValue == ''"
            >
              <h3>热搜榜</h3>
              <ul>
                <li
                  v-for="(item, index) in searchHotList"
                  :key="index"
                  @click="gotoSong(item)"
                >
                  <div class="no">
                    <span
                      :style="{ color: index < 3 ? 'rgb(255, 58, 58)' : '' }"
                      >{{ index + 1 }}</span
                    >
                  </div>
                  <div class="info">
                    <div class="name">
                      <span>{{ item.searchWord }}</span>
                      <span>{{ item.score }}</span>
                      <img
                        v-lazy="item.iconUrl"
                        v-show="item.iconType == 1"
                        class="hotIcno"
                      />
                    </div>
                    <div class="content" v-show="item.content != ''">
                      <span>{{ item.content }}</span>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </transition>
          <transition name="fade">
            <!-- v-show="inputValue != ''" -->
            <div
              class="searchSuggest"
              v-show="inputValue != '' && suggestShow == true"
            >
              <div class="songs">
                <div class="songsTitle">
                  <i class="songsIcno"></i>
                  <span>单曲</span>
                </div>
                <div class="songsRes">
                  <ul>
                    <li v-for="(item, index) in songs" :key="index">
                      <span>{{ item.name }}</span>
                      <span> - </span>
                      <span
                        v-for="(songsItem, songsIndex) in item.artists"
                        :key="songsIndex"
                      >
                        {{ songsItem.name }}
                      </span>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="artists">
                <div class="artTitle">
                  <i class="artIcno"></i>
                  <span>歌手</span>
                </div>
                <div class="artRes">
                  <ul>
                    <li v-for="(item, index) in artists" :key="index">
                      <span>{{ item.name }}</span>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="albums">
                <div class="albumsTitle">
                  <i class="albumsIcno"></i>
                  <span>专辑</span>
                </div>
                <div class="albumsRes">
                  <ul>
                    <li v-for="(item, index) in albums" :key="index">
                      <span>{{ item.name }}</span>
                      <span> - </span>
                      <span>{{ item.artist.name }}</span>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </transition>
          <div class="inputBack"></div>
          <input
            type="text"
            :placeholder="inputMoRen"
            @blur="blur"
            @focus="search"
            v-model="inputValue"
            @input="input"
            @keyup.enter="gotoSearch"
          />
        </div>
        <div class="user">
          <div class="login">
            <span>登录</span>
            <span>注册</span>
          </div>
        </div>
      </header>
    </transition>

    <main>
      <router-view></router-view>
    </main>
    <transition name="img-fade">
      <div class="geci" ref="geci" v-show="picShow == true">
        <img :src="picUrl" alt="" />
      </div>
    </transition>
    <!-- 播放列表 -->
    <transition name="fade"> </transition>
    <transition name="fade">
      <div class="playFather" v-show="playFlag == true">
        <div id="play">
          <div
            class="process"
            ref="progressBar"
            @click="clickProgress($event)"
            @mouseover="btnShow = true"
            @mouseleave="btnShow = false"
          >
            <div class="line" ref="progress"></div>
            <transition name="fade">
              <div
                class="dot"
                @touchstart="dotStart"
                @touchmove="dotMove"
                @touchend="dotEnd"
                ref="progressBtn"
                v-show="btnShow"
              ></div>
            </transition>
          </div>
          <div class="bottom">
            <div class="info" v-show="name != null">
              <div class="top">
                <i class="topIcno"></i>
              </div>
              <div class="img">
                <img v-lazy="picUrl" alt="" v-show="picUrl != ''" />
              </div>
              <div class="name">
                <div class="singName">
                  <span>{{ name }}</span>
                  <span v-show="alias != undefined || alias != null"
                    >({{ alias }})</span
                  >
                </div>
                <div class="artName">
                  <span v-for="(item, index) in artName" :key="index">
                    {{ item.name }}
                  </span>
                </div>
              </div>
            </div>
            <div class="info" v-show="name == null">
              <span>暂时还未播放歌曲~~</span>
            </div>
            <div class="audioPlay">
              <audio
                ref="audio"
                @timeupdate="updateTime"
                @canplay="getDuration"
                @ended="ended"
                :src="audio_url"
              >
                您的浏览器不支持 audio 元素。
              </audio>
              <div class="tidai">
                <div class="playLeft">
                  <div class="controls">
                    <div class="playWay">
                      <i class="wayIcno"></i>
                    </div>
                    <div class="pre" @click="prevSong">
                      <i class="preIcno"></i>
                    </div>
                    <!--  -->
                    <div class="pause" v-show="isPlaying" @click="pauseSong">
                      <i class="pauseIcno"></i>
                    </div>
                    <div class="play" v-show="!isPlaying" @click="playSong">
                      <i class="playIcno"></i>
                    </div>
                    <div class="next" @click="nextSong">
                      <i class="nextIcno"></i>
                    </div>
                    <div class="ci">
                      <i class="ciIcno"></i>
                    </div>
                  </div>
                  <div class="progress">
                    <div class="curTime">
                      <span>{{ curTime }}</span>
                    </div>
                    <div class="fenge">
                      <span>/</span>
                    </div>
                    <div class="allTime">
                      <span>{{ allTime }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="playRight">
              <i class="listIcno" @click="showList"></i>
            </div>
          </div>
          <div class="playList" v-show="listShow == true">
            <div class="title">
              <h3>当前播放</h3>
              <div>
                <span
                  >总<span>{{ allSongsList.length }}</span
                  >首</span
                >
                <span style="color: rgb(255, 165, 0)" @click="cleanList"
                  >清除列表</span
                >
              </div>
            </div>
            <div class="list">
              <ul>
                <li
                  v-for="(item, index) in allSongsList"
                  :key="index"
                  @click="playListSong(item)"
                >
                  <span class="allname">
                    <span>{{ item.name }}</span>
                    <span
                      v-show="item.alia.length > 0"
                      style="color: #999; font-size: 12px"
                      >({{ item.alia[0] }})</span
                    >
                  </span>
                  <span class="allartName"
                    ><span
                      v-for="(nameItem, nameIndex) in item.ar"
                      :key="nameIndex"
                      >{{ nameItem.name }}</span
                    ></span
                  >
                  <span class="allalName">{{ item.al.name }}</span>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <transition name="fade">
      <div class="icno" v-show="playFlag == false">
        <div id="playIcno" ref="playIcno">
          <img src="../assets/play.png" v-show="picUrl == ''" />
          <!-- <img :src="picUrl" v-show="picUrl != ''" /> -->
          <img src="../assets/logo.jpg" v-show="picUrl != ''" />
          <i
            class="pauseSmallIcno"
            v-show="isPlaying == false"
            @click="playSong"
          ></i>
          <i
            class="playSmallIcno"
            v-show="isPlaying == true"
            @click="pauseSong"
          ></i>
        </div>
      </div>
    </transition>
    <!-- <div id="login">
      <div class="loginArea">
        <div class="choose">
          <span>验证码登录</span>
          <span>密码登录</span>
        </div>
        <div class="loginInput"></div>
      </div>
    </div> -->
    <div class="register"></div>
  </div>
</template>

<script>
import homePage from "@/pages/homePages/homePage.vue";
export default {
  name: "top",
  components: {
    homePage,
  },
  data() {
    return {
      // 当前播放共多少首歌
      listNumber: 0,
      // 导航栏是否显示
      navShow: true,
      // 热搜榜
      searchHotList: [],
      // s是否显示热搜榜
      searchHotShow: false,
      // 播放器图片
      // picUrl: "",
      picUrl: "",
      // 歌曲名字
      name: null,
      // 副标题
      alias: null,
      // 歌手
      artName: [],
      // 音频播放地址
      audio_url: "",
      // 导航选中
      num: 0,
      // 输入框输入内容
      inputValue: "", // 是否显示默认
      inputMoRen: null,
      // 搜索建议是否显示
      suggestShow: true,
      placeholder: null,
      // 搜索结果建议
      // 单曲
      songs: [],
      // 歌手
      artists: [],
      // 专辑
      albums: [],
      navList: [
        {
          num: 0,
          value: "发现音乐",
        },
        {
          num: 1,
          value: "主播电台",
        },
        {
          num: 2,
          value: "MV",
        },
        {
          num: 3,
          value: "私人FM",
        },
        {
          num: 4,
          value: "我的音乐",
        },
      ],
      // 获取歌单歌曲
      allSongsList: [],
      // 列表是否显示
      listShow: false,

      // 进度条现在时间
      curTime: "00:00",
      // 歌曲所有时间
      allTime: "00:00",
      // 音频总时长
      duration: 0,
      // 显示播放还是暂停键
      isPlaying: false,
      // 是否显示封片图片
      picShow: false,
      // 进度条
      percent: null,
      // 时间是否显示
      timeShow: false,
      // 音频当前播放时间
      currentTime: 0,
      // 播放类型
      playType: 0, // 0表示单曲 1表示播放的是歌曲列表
      // 原点滑动时的位置信息
      touchInfo: {
        initiated: false,
      },
      // 按钮长度
      btnWidth: 0,

      scrollTop: 0,
      // 是否显示底部播放
      playFlag: true,
      // 小圆点是否显示
      btnShow: false,

      // 当前播放列表是否有该首歌曲
      exit: 0,

      // 当前播放的是播放列表的第几首歌
      curPlaySongIndex: 0,
    };
  },
  methods: {
    // 点击搜索框时是否显示默认文字
    search() {
      if (this.inputValue != "") {
        this.inputMoRen = "";
        this.suggestShow = true;
      } else {
        this.inputMoRen = this.placeholder;
        this.searchHotShow = true;
      }
    },
    // 失去焦点显示文字
    blur() {
      this.inputMoRen = this.placeholder;
      this.searchHotShow = false;
      this.suggestShow = false;
    },
    // 监听输入事件
    input() {
      if (this.inputValue != "") {
        this.inputMoRen = "";
        // 多重匹配
        this.$axios({
          url: "/search/suggest",
          params: {
            keywords: this.inputValue,
          },
        }).then((res) => {
          this.songs = res.data.result.songs;
          this.artists = res.data.result.artists;
          this.albums = res.data.result.albums;
          this.suggestShow = true;
        });
      } else {
        this.inputMoRen = this.placeholder;
        this.searchHotShow = true;
      }
    },
    // 导航选中更改样式及跳转
    navChoose(index) {
      this.num = index;
      switch (index) {
        case 0:
          this.$router.replace("/homePage");
          break;
        case 1:
          this.$router.replace("/diantai");
          break;
        case 2:
          this.$router.replace("/mv");
          break;
      }
    },
    // 点击热搜榜后跳转
    gotoSong(item) {
      this.inputValue = item.searchWord;
    },
    // 回车前往搜索结果页
    gotoSearch() {
      this.$router.replace({
        name: "search",
        query: {
          keywords: this.inputValue,
        },
      });
    },
    // 暂停音乐
    pauseSong() {
      this.isPlaying = !this.isPlaying;
      this.$refs.audio.pause();
      this.$refs.geci.classList.add("rotatePause");
      this.$refs.playIcno.classList.add("rotatePause");
    },
    // 手动播放音乐
    playSong() {
      if (this.audio_url == "") {
        this.$message.warning("还未选择单曲或歌单播放~");
        return;
      }
      const audio = this.$refs.audio;
      this.isPlaying = !this.isPlaying;
      audio.play();
      this.$refs.geci.classList.add("rotate");
      if (this.$refs.geci.classList.contains("rotatePause")) {
        this.$refs.geci.classList.remove("rotatePause");
      }
      this.$refs.playIcno.classList.add("rotate");
      if (this.$refs.playIcno.classList.contains("rotatePause")) {
        this.$refs.playIcno.classList.remove("rotatePause");
      }
    },
    // 自动播放音乐
    autoPlaySong() {
      const audio = this.$refs.audio;
      audio.autoplay = true;
      this.isPlaying = true;
      this.$refs.geci.classList.add("rotate");
      if (this.$refs.geci.classList.contains("rotatePause")) {
        this.$refs.geci.classList.remove("rotatePause");
      }
      this.$refs.playIcno.classList.add("rotate");
      if (this.$refs.playIcno.classList.contains("rotatePause")) {
        this.$refs.playIcno.classList.remove("rotatePause");
      }
    },

    // 上一首
    prevSong() {
      this.curPlaySongIndex--;
      if (this.curPlaySongIndex < 0) {
        this.curPlaySongIndex = this.allSongsList.length - 1;
      }
      this.playListSong(this.allSongsList[this.curPlaySongIndex]);
    },

    // 下一首
    nextSong() {
      this.curPlaySongIndex++;
      if (this.curPlaySongIndex > this.allSongsList.length) {
        this.curPlaySongIndex = 0;
      }
      this.playListSong(this.allSongsList[this.curPlaySongIndex]);
    },

    // 格式化 获取mm:ss格式的时间
    formatTime(time) {
      if (time === 0) {
        this.curTime = "00:00";
        return;
      }
      const mins =
        Math.floor(time / 60) < 10
          ? `0${Math.floor(time / 60)}`
          : Math.floor(time / 60);
      const sec =
        Math.floor(time % 60) < 10
          ? `0${Math.floor(time % 60)}`
          : Math.floor(time % 60);
      return `${mins}:${sec}`;
    },

    // 拿到当前时间 更新进度条
    // 获取当前播放时间
    updateTime(e) {
      const { currentTime } = e.target;
      this.currentTime = currentTime;
      this.curTime = this.formatTime(currentTime);
      this.updateProgress(this.currentTime, this.duration);
      // 匹配歌词
    },

    // 获取音乐总时长 canplay时获取总时长
    getDuration() {
      this.duration = this.$refs.audio.duration;
      this.allTime = this.formatTime(this.$refs.audio.duration);
    },

    // ended
    ended() {
      this.$refs.geci.classList.remove("rotate");
      this.$refs.audio.currentTime = 0;
      this.isPlaying = false;
      if (this.playType === 0) {
        this.$message.warning("当前播放为单曲~");
        this.curTime = "00:00";
        return;
      }
      // 播放下一首
    },

    // 更新进度条
    updateProgress(currentTime, duration) {
      const percent = `${currentTime / duration}`;
      this.percent = percent;
    },

    // 点击进度条时 更新音频时间和进度条
    clickProgress(event) {
      // 设置进度条及按钮偏移
      this._setOffset(event.offsetX);
      const e = event || window.event;
      const position = e.clientX - e.currentTarget.offsetLeft; // 当前点击的位置
      const progressWidth = this.$refs.progressBar.offsetWidth; // 进度总长度
      this.$refs.audio.currentTime = (position / progressWidth) * this.duration;
      this.updateProgress(
        (position / progressWidth) * this.duration,
        this.duration
      );
      // 通知父组件播放进度变化
      // this._triggerPercent();

      //
    },

    dotStart(e) {
      // touch事件已经初始化
      this.touchInfo.initiated = true;
      // 点击的初始位置
      this.touchInfo.startX = e.touches[0].pagesX;
      // 点击时进度条的长度
      this.touchInfo.left = this.$refs.progress.clientWidth;
    },

    dotMove(e) {
      if (!this.touchInfo.initiated) {
        return;
      }
      // 移动的距离
      // let moveX = e.touches[0].pageX;
      let moveX = e.touches[0].pageX - this.touchInfo.startX;
      //  设置偏移值
      const offsetWidth = Math.min(
        Math.max(0, this.touchInfo.left + moveX),
        this.$refs.progressBar.clientWidth - this.btnWidth
      );
      this._setOffset(offsetWidth);
    },

    // 设置偏移
    _setOffset(offsetWidth) {
      // 设置进度长度随着百分比变化
      this.$refs.progress.style.width = `${offsetWidth}px`;
      // 设置按钮随着百分比偏移
      this.$refs.progressBtn.style.transform = `translate3d(${offsetWidth}px, 0, 0)`;
    },

    dotEnd() {
      this.touchInfo.initiated = false;
      this.playSong();
      this.isPlaying = true;
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop < 60) {
        that.playFlag = true;
      } else {
        that.playFlag = false;
      }
    },

    // 点击播放列表歌曲 播放
    playListSong(item) {
      this.$axios({
        url: "/song/url",
        params: {
          id: item.id,
        },
      }).then((res) => {
        let url = res.data.data[0].url;
        let data = {
          url,
          item,
        };
        this.$bus.$emit("get-src", data);
      });
    },

    // 清除列表
    cleanList() {
      this.allSongsList = [];
      this.listNumber = 0;
    },

    // 显示列表
    showList() {
      this.listShow = !this.listShow;
    },
  },
  created() {
    // 获取默认搜索词
    this.$axios({
      url: "/search/default",
    }).then((res) => {
      this.placeholder = res.data.data.showKeyword;
      this.inputMoRen = this.placeholder;
    });

    // 获取热搜关键词
    this.$axios({
      url: "/search/hot/detail",
    }).then((res) => {
      this.searchHotList = res.data.data.slice(0, 10);
    });
  },
  mounted() {
    this.btnWidth = document.getElementsByClassName("dot").clientWidth;
    let _this = this;
    this.$bus.$on("get-src", function (data) {
      setTimeout(function () {
        _this.$refs.audio.src = data.url;
        _this.allSongsList.forEach((element) => {
          if (element.name == data.item.name) {
            _this.exit = 1;
          }
        });
        if (_this.exit === 0) {
          _this.allSongsList.push(data.item);
        }
        _this.audio_url = data.url;
        _this.picUrl = data.item.al.picUrl;
        _this.name = data.item.name;
        _this.alias = data.item.alia[0];
        _this.artName = data.item.ar;
        // 自动播放
        _this.$refs.audio.autoplay = true;
        _this.isPlaying = true;
        _this.$refs.geci.classList.add("rotate");
        if (_this.$refs.geci.classList.contains("rotatePause")) {
          _this.$refs.geci.classList.remove("rotatePause");
        }
        _this.$refs.playIcno.classList.add("rotate");
        if (_this.$refs.playIcno.classList.contains("rotatePause")) {
          _this.$refs.playIcno.classList.remove("rotatePause");
        }
      });
    });

    window.addEventListener("scroll", this.scrollToTop);

    // 获取歌单歌曲
    this.$bus.$on("get-songsLists", function (data) {
      setTimeout(() => {
        _this.allSongsList = data;
        _this.listNumber = data.length;
        _this.playListSong(_this.allSongsList[_this.curPlaySongIndex]);
      });
    });
  },

  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop);
  },
  watch: {
    currentTime(newTime, oldTime) {
      this.updateProgress(newTime, this.duration);
    },
    // 监听歌曲播放百分比变化
    percent(newPercent, oldPercent) {
      if (newPercent > 0) {
        // 进度条总长度
        const barWidth = this.$refs.progressBar.clientWidth;
        const offsetWidth = barWidth * newPercent;
        // 设置进度条及按钮偏移
        this._setOffset(offsetWidth);
      }
    },
    audio_url(newUrl, oldUrl) {
      this._setOffset(0);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
@import url("../css/top");
</style>
